let { customer } = require('../modules/customerModules');
const { removeFiles, moveFiles } = require('../utils/upload')
//渲染
module.exports.getCustomer = async (req, res) => {
     let { pageSize = 5, currentPage = 1 } = req.query;
     // 总条数
     const total = await customer.countDocuments();
     //总页数
     const totalPages = Math.ceil(total / pageSize);
     let data = await customer.find().populate({
          path: 'salesmanId',
     }).limit(pageSize - 0).skip((currentPage - 1) * pageSize);
     if (data.length > 0) {
          res.send({
               status: 1,
               msg: '获取客户列表成功',
               data: { data, total, totalPages, currentPage }
          })
     }
}
// 添加
module.exports.addCustomer = async (req, res, next) => {
     let { username, password, state, brith = '', tel, img, nickName,salesmanId} = req.body;
     if (img) {
          //移动文件夹
          moveFiles({ formPath: './public/temp', toPath: './public/images', filename: img });
          //删除文件夹
          removeFiles('./public/temp');
     }
     let info = await customer.create({ username, password, brith, state, tel, img,salesmanId });
     if (info._id) {
          res.send({
               status: 1,
               msg: '添加客户成功'
          })
     } else {
          res.send({
               status: 0,
               msg: '添加客户失败'
          })
     }
}
// 删除
module.exports.delCustomer = async (req, res, next) => {
     let { _id } = req.body;

     let info = await customer.deleteOne({ _id });
     console.log('删除信息', info);
     if (info.deletedCount) {
          console.log(232)
          res.send({
               status: 0,
               msg: '删除成功'
          })
     }
}
// 得到一个客户信息修改
module.exports.getOneCustomer = async (req, res) => {
     let { _id } = req.params;
     let data = await customer.find({ _id });
     console.log('客户', data)
     if (data.length > 0) {
          res.send({
               status: 1,
               msg: '获取一个客户成功',
               data
          })
     } else {
          res.send({
               status: 1,
               msg: '修改失败',

          })
     }
}
module.exports.update = async (req, res) => {

     let { _id, username, password, brith, state, tel, img, nickName } = req.body;
     let data = await customer.updateOne({ _id }, { username, password, state, tel, img, nickName });
     if (data.nModified) {
          res.send({
               status: 1,
               msg: '修改成功',
          })
     } else {
          res.send({
               status: 0,
               msg: '修改失败',
          })
     }
} 
